package org.poptest.util;

import org.poptest.model.Predicate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Collection Utilities
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * @author Alan Roche
 *         Date: 17/02/11
 *         Time: 21:31
 */
public final class CollectionUtils {

    /**
     * Returns a list of items that match the predicate
     * @param items
     * @param predicate
     * @param <T>
     * @return
     */
    public static <T> List<T> select(final Collection<T> items, final Predicate<T> predicate) {
        final List<T> matches = new ArrayList<T>() ;
        for (final T item : items) {
            if (predicate.isMatch(item)) {
                matches.add(item);
            }
        }
        return matches;
    }

    public static <T> T findFirst(final Collection<T> items, final Predicate<T> predicate) {
        T match = null;
        for (final T item : items) {
            if (predicate.isMatch(item)) {
                match = item;
                break;
            }
        }
        return match;
    }
}
